package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.PageDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private CategoryBrandService categoryBrandService;

    @Autowired
    private BrandMapper brandMapper;
    /**
     * 根据分类id集合新增品牌
     * @param brandDTO 品牌DTO，其中封装了分类id集合
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertBrandByIds(BrandDTO brandDTO) {

        Brand brand = brandDTO.toEntity(Brand.class);
        this.save(brand);
        //通过品牌id和分类id集合组合出中间表对象
        List<CategoryBrand> categoryBrandList = brandDTO.getCategoryIds().stream()
                .map(cid -> CategoryBrand.of(cid,brand.getId()))
                .collect(Collectors.toList());

        categoryBrandService.saveBatch(categoryBrandList);
    }

    /**
     * 分局传入的DTO对象修改品牌数据
     * @param brandDTO 品牌DTO，其中封装了分类id集合
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        //根据主键id修改品牌信息
        boolean bl = updateById(brand);
        if (!bl) {
            throw new LyException(500, "更新品牌失败！");
        }
        //先删除中间表关联信息，再重新添加中间表关联
        boolean b =  categoryBrandService.remove(
                new QueryWrapper<CategoryBrand>().eq("brand_id", brandDTO.getId()));
        if (!b) {
            throw new LyException(500,"删除中间表失败");
        }
        List<CategoryBrand> categoryBrandList = brandDTO.getCategoryIds().stream()
                .map(cid -> CategoryBrand.of(cid, brandDTO.getId()))
                .collect(Collectors.toList());
        categoryBrandService.saveBatch(categoryBrandList);

    }

    /**
     * 根据品牌id集合查询品牌集合
     * @return
     */
    @Override
    public List<BrandDTO> findByIds(List<Long> ids) {

        return BrandDTO.convertEntityList(listByIds(ids));
    }

    /**
     * 根据分类id查询品牌
     * @param cid 分类id
     * @return
     */
    @Override
    public List<BrandDTO> findById(Long cid) {
        return BrandDTO.convertEntityList(brandMapper.findById(cid));
    }

    /**
     * 分页查询品牌
     * @param key 搜索条件
     * @param page 当前页
     * @param rows 每页大小
     * @return
     */
    @Override
    public PageDTO<BrandDTO> findPage(String key, Long page, Long rows) {

        IPage<Brand> iPage = new Page<>(page, rows);
        boolean empty = StringUtils.isNoneEmpty(key);
        page(iPage, new QueryWrapper<Brand>().like(empty, "name", key).or().eq(empty, "letter", key));
        return new PageDTO<BrandDTO>(iPage.getTotal(), iPage.getPages(), BrandDTO.convertEntityList(iPage.getRecords()));
    }

    /**
     * 根据品牌id查询品牌
     * @param id 品牌id
     * @return
     */
    @Override
    public BrandDTO findByBrandId(Long id) {
        return new BrandDTO(this.getById(id));
    }

    /**
     * 根据品牌id删除品牌
     * @param id 品牌id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByBrandId(Long id) {
        boolean b = this.removeById(id);
        if (!b) {
            throw new LyException(500,"删除品牌出现错误");
        }
        boolean bl = categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", id));
        if (!bl) {
            throw new LyException(500,"删除品牌-分类中间表出现错误");
        }
    }
}
